package com.li.o2oSystem.web.shopadmin;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.li.o2oSystem.dto.ImageHolder;
import com.li.o2oSystem.dto.ProductExecution;
import com.li.o2oSystem.entity.Product;
import com.li.o2oSystem.entity.ProductCategory;
import com.li.o2oSystem.entity.Shop;
import com.li.o2oSystem.enums.ProductStateEnum;
import com.li.o2oSystem.exceptions.ProductOperationException;
import com.li.o2oSystem.exceptions.ShopOperationException;
import com.li.o2oSystem.service.ProductCategoryService;
import com.li.o2oSystem.service.ProductService;
import com.li.o2oSystem.util.CodeUtil;
import com.li.o2oSystem.util.HttpServletRequestUtil;

@Controller
@RequestMapping(value="/shopadmin")
public class ProductManagementController {
	@Autowired
	private ProductService productService;
	@Autowired
	private ProductCategoryService productCategoryService;
	//支持商品详情图的最大数量
	private static final int IMAGEMAXCOUNT = 6;

	@SuppressWarnings("unused")
	@RequestMapping(value="/addproduct",method=RequestMethod.POST)
	@ResponseBody
	private Map<String,Object> addProduct(HttpServletRequest request){
		Map<String,Object> modelMap = new HashMap<>();
		//校验验证码
		if(!CodeUtil.checkVerifyCode(request)){
			modelMap.put("success", false);
			modelMap.put("errMsg", "验证码输入错误。");
			return modelMap;
		}
		//接受前端参数的变量的初始化，包括商品，缩略图，详情图列表实体类
		ObjectMapper mapper = new ObjectMapper();
		Product product = null;
		String productStr = HttpServletRequestUtil.getString(request, "productStr");
		ImageHolder  thumbnail = null;//处理缩略图
		List<ImageHolder> productImgList = new ArrayList<>();//处理商品详情图
		CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());//解析请求中的文件流
		try {
			//若请求中存在文件流，则取出相关的文件，（包括缩略图和商品详情图）
			if(multipartResolver.isMultipart(request)){
				thumbnail = handleImage(request, thumbnail, productImgList);
			}
			else{
				modelMap.put("success", false);
				modelMap.put("errMsg", "上传图片不能为空");
				return modelMap;
			}
		} catch (Exception e) {
			modelMap.put("success", false);
			modelMap.put("errMsg", "上传图片处理异常"+e.getMessage());
			return modelMap;
		}
		try {
			//尝试获取前端穿过来的表单String流，并将其装换为Product实体类
			product = mapper.readValue(productStr,Product.class);
		} catch (Exception e) {
			modelMap.put("success", false);
			modelMap.put("errMsg", "前端对象转换异常："+e.getMessage());
			return modelMap;
		}
		//若product信息，缩略图以及详情图列表为非空，则开始进行商品添加操作
		if(product != null && thumbnail != null && productImgList.size() >= 0){
			try {
				//从session中获取当前店铺的id并赋值给product，减少对前端数据的依赖
				Shop currentShop = (Shop) request.getSession().getAttribute("currentShop");
				product.setShop(currentShop);
				//执行添加操作
				ProductExecution pe = productService.addProduct(product, thumbnail, productImgList);
				if(pe.getState() == ProductStateEnum.SUCCESS.getState()){//若pe返回的操作状态标识为成功
					modelMap.put("success", true);
				}
				else{
					modelMap.put("success", false);
					modelMap.put("errMsg", pe.getStateInfo());
				}
			} catch (ProductOperationException e) {
				modelMap.put("success", false);
				modelMap.put("errMsg", "店铺添加异常："+e.getMessage());
				return modelMap;
			}
		}
		else{
			modelMap.put("success", false);
			modelMap.put("errMsg", "请输入商品信息！");
		}
		return modelMap;
	}
	/**
	 * 根据商品id查询商品信息
	 * @param productId
	 * @return
	 */
	@RequestMapping(value="/getproductbyid",method=RequestMethod.GET)
	@ResponseBody
	private Map<String,Object> getProductById(@RequestParam Long productId){
		Map<String,Object> modelMap = new HashMap<>();
		//非空判断
		if(productId > -1){
			//获取商品信息
			Product product = productService.getProductById(productId);
			//获取店铺下的商品类别列表
			List<ProductCategory> productCategoryList = productCategoryService.getProductCategory(product.getShop().getShopId());
			modelMap.put("product", product);
			modelMap.put("productCategoryList", productCategoryList);
			modelMap.put("success", true);
		}
		else{
			modelMap.put("success", false);
			modelMap.put("errMsg", "empty productId");
		}
		return modelMap;
	}
	/**
	 * 修改商品信息
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/modifyproduct",method=RequestMethod.POST)
	@ResponseBody
	private Map<String,Object> modifyProduct(HttpServletRequest request){
		Map<String,Object> modelMap = new HashMap<>();
		/*是商品编辑时调用，还是上下架时调用
		 *若为前者，则进行验证码判断，后者，跳过验证码判断
		 */
		boolean statusChange = HttpServletRequestUtil.getBoolean(request, "statusChange");
		//验证码判断
		if(!statusChange && !CodeUtil.checkVerifyCode(request)){
			modelMap.put("success", false);
			modelMap.put("errMsg", "验证码错误");
			return modelMap;
		}
		//接受前端参数的变量的初始化，包括商品，缩略图，详情图列表
		ObjectMapper mapper = new ObjectMapper();
		Product product = null;
		ImageHolder thumbnail = null;
		List<ImageHolder> productImgList = new ArrayList<>();
		CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
		//若请求中存在文件流，则取出相关的文件（保留缩略图和详情图）
		try {
			if(multipartResolver.isMultipart(request)){
				thumbnail = handleImage(request, thumbnail, productImgList);
			}
		} catch (Exception e) {
			modelMap.put("success", false);
			modelMap.put("errMsg", "图片处理异常："+e.getMessage());
			return modelMap;
		}
		try {
			String productStr = HttpServletRequestUtil.getString(request, "productStr");
			//获取前端传来的String流，并将其转换为Product实体类
			product = mapper.readValue(productStr, Product.class);
		} catch (Exception e) {
			modelMap.put("success", false);
			modelMap.put("errMsg", "前端json对象转换异常："+e.getMessage());
			e.printStackTrace();
			return modelMap;
		}
		//非空判断
		if(product != null){
			try {
				//从session中获取，当前店铺id，并赋值给product ,减少对前端数据的依赖
				Shop currentShop = (Shop) request.getSession().getAttribute("currentShop");
				product.setShop(currentShop);
				//商品信息修改操作
				ProductExecution pe = productService.modifyProduct(product, thumbnail, productImgList);
				if(pe.getState() == ProductStateEnum.SUCCESS.getState()){
					modelMap.put("success", true);
				}
				else{
					modelMap.put("success", false);
					modelMap.put("errMsg", "商品修改失败："+pe.getStateInfo());
				}
			} catch (RuntimeException e) {
				modelMap.put("success", false);
				modelMap.put("errMsg", "商品修改异常："+e.getMessage());
				return modelMap;
			}
			
		}
		else{
			modelMap.put("success", false);
			modelMap.put("errMsg", "请输入商品信息");
		}
		return modelMap;
	}
	/**
	 * 处理图片方法
	 * @param request
	 * @param thumbnail
	 * @param productImgList
	 * @return 
	 * @throws IOException
	 */
	private ImageHolder handleImage(HttpServletRequest request, ImageHolder thumbnail, List<ImageHolder> productImgList)
			throws IOException {
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		//取出缩略图并构建ImageHolder对象
		CommonsMultipartFile thumbnailFile = (CommonsMultipartFile) multipartRequest.getFile("thumbnail");
		if(thumbnailFile!= null){
			thumbnail = new ImageHolder(thumbnailFile.getOriginalFilename(),thumbnailFile.getInputStream());
		}
		//取出详情图列表并构建List<ImageHolder> 列表对象，最多支持6张图片上传
		for(int i =0;i < IMAGEMAXCOUNT;i++){
			CommonsMultipartFile productImgFile = (CommonsMultipartFile) multipartRequest.getFile("productImg"+i);
			if(productImgFile != null){
				//取出第i个详情图文件流不为空，则将其加入详情图列表
				ImageHolder productImg = new ImageHolder(productImgFile.getOriginalFilename(),productImgFile.getInputStream());
				productImgList.add(productImg);
			}
			else{
				//若取出的第i个详情图片文件流为空，则终止循环
				break;
			}
		}
		return thumbnail;
	}
	/**
	 * 根据条件分页获取商品信息列表
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/getproductlistbyshop",method=RequestMethod.GET)
	@ResponseBody
	private Map<String,Object> getProductListByShop(HttpServletRequest request){
		Map<String,Object> modelMap = new HashMap<>();
		//获取前台传过来的的页码
		int pageIndex = HttpServletRequestUtil.getInt(request, "pageIndex");
		//获取前台要显示商品的条数
		int pageSize = HttpServletRequestUtil.getInt(request, "pageSize");
		//从session中获取店铺信息，主要获取店铺id
		Shop currentShop = (Shop) request.getSession().getAttribute("currentShop");
		//空值判断
		if((pageIndex > -1) && (pageSize > -1) && (currentShop != null) && (currentShop.getShopId() != null)){
			//获取分页查询的条件
			long productCategoryId = HttpServletRequestUtil.getLong(request, "productCategoryId");
			String productName = HttpServletRequestUtil.getString(request, "productName");
			Product productCondition = compactProductCondition(currentShop.getShopId(),productCategoryId,productName);
			//传入分页查询的条件及分页信息进行查询，返回相应商品列表，及总数
			ProductExecution pe = productService.getProductList(productCondition, pageIndex, pageSize);
			modelMap.put("success", true);
			modelMap.put("count", pe.getCount());
			modelMap.put("productList", pe.getProductList());
		}
		else{
			modelMap.put("success", false);
			modelMap.put("errMsg", "empty pageSize or pageIndex or shopId");
		}
		return modelMap;
	}
	/**
	 * 封装商品查询条件到Product实例中
	 * @param shopId
	 * @param productCategoryId
	 * @param productName
	 * @return
	 */
	private Product compactProductCondition(Long shopId, long productCategoryId, String productName) {
		Product productCondition = new Product();
		Shop shop = new Shop();
		shop.setShopId(shopId);
		productCondition.setShop(shop);
		//若有指定类别，则添加类别条件
		if(productCategoryId != -1L){
			ProductCategory productCategory = new ProductCategory();
			productCategory.setProductCategoryId(productCategoryId);
			productCondition.setProductCategory(productCategory);
		}
		//若有商品名称模糊查询
		if(productName != null){
			productCondition.setProductName(productName);
		}
		return productCondition;
	}
}
